﻿using System;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Security.Principal;

namespace DomusDotNet.Sbm.Client.SL4noCM.Services
{

    public class DefaultSecurityContext : ISecurityContext {

        readonly string KEY = typeof(DefaultSecurityContext).FullName + "/CurrentPrincipal";

        public DefaultSecurityContext() {
            string userName = null;
            IsolatedStorageSettings.ApplicationSettings.TryGetValue(KEY, out userName);
            CurrentUser = userName == null ? DefaultPrincipal.Null : new DefaultPrincipal(userName, Guid.Empty);   
        }


        IPrincipal currentUser;
        public IPrincipal CurrentUser {
            get { return currentUser; }
            set
            {
                currentUser = value;
                IsolatedStorageSettings.ApplicationSettings[KEY] = value.Identity.IsAuthenticated ? value.Identity.Name : null;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        public event EventHandler CurrentUserChanged = delegate { };

        private string sessionGUID;
        public string SessionGUID
        {
            get
            {
                return sessionGUID;
            }
            set
            {
                //if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException();
                sessionGUID = value;
            }
        }
    }


    public interface IIdentityWithToken : IIdentity
    {
        Guid LoginToken { get; }
    }

    public class DefaultPrincipal : IPrincipal, IIdentityWithToken
    {
        public static readonly IPrincipal Null = new DefaultPrincipal();

        private DefaultPrincipal()
        {
            IsAuthenticated = false;
        }
        public DefaultPrincipal(string name, Guid token)
        {
            Name = name;
            LoginToken = token;
            IsAuthenticated = true;
        }

        public IIdentity Identity { get { return this; } }
        public bool IsInRole(string role)
        {
            return true;
        }


        public string AuthenticationType
        {
            get { return null; }
        }

        public bool IsAuthenticated { get; private set; }
        public string Name { get; private set; }
        public Guid LoginToken { get; private set; }

    }

}
